<?php
namespace app\admin\model;

class Module extends ModelCore
{
	//写入完成
	protected $auto = [
		'update_time'
	];
	//新增完成
    protected $insert = [
		'create_time'
	];  
	//更新完成
    protected $update = []; 
	
	/**
     * 获取模块列表
     * @param string $addon_dir
     */
    public function _List($start=0,$limit=9999){
		$_Dir = APP_PATH;
        $_Objs = array_map('basename',glob($_Dir.'*', GLOB_ONLYDIR));
        if($_Objs === false || !file_exists($_Dir)){
            $this->error = '模块目录不可读或者不存在';
            return false;
        }
		//设置空变量，作为存储插件信息的变量
		$_Arr=array();
		foreach($_Objs as $_Obj){
			if(in_array($_Obj,['common','lang','plug'])){
				continue;
			}
			//设置当前模块的配置路径
			$_CPath = $_Dir .  $_Obj . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config.php';
			//如果配置不存在，则返回错误
			if (!file_exists($_CPath)) {
				continue;
			}
			
			//引入配置文件
			$_Conf = require $_CPath;
			//设置config信息
			$_Conf['status'] = -1;
			$_Conf['create_time'] = 0;
			if(isset($_Conf['setting'])){
				$_Conf['is_conf'] = 1;
			}else{
				$_Conf['is_conf'] = 0;
			}
			$_Arr[$_Obj]=$_Conf;
			
		}
		//获取所有的已安装的模块
		$_List = $this->select();
		//对于前面从数据库中获取的插件记录，进行操作
		foreach($_List as $_Obj){
			$_Arr[$_Obj['name']] = array_merge($_Arr[$_Obj['name']],$_Obj->toArray());
		}
        $_Arr = _Arr_Sorts($_Arr,'status',SORT_DESC,'create_time',SORT_ASC);
		$_Return = [];
		foreach($_Arr as $V){
			if($V['create_time']<1){
				$V['create_time'] = '';
			}
			$_Return[] = $V;
		}
		if($limit != 9999){
			$_Return = array_slice($_Return,$start,$limit);
		}
        return $_Return;
    }
	
	//事件监听
	protected static function init()
    {
		//写入前
		//self::event('before_write', function ($_Data) {});
		//写入后
		self::event('after_write', function ($_Data) {
			model('app\admin\logic\Module')->_ResetCache();
		});
		//新增前
		//self::event('before_insert', function ($_Data) {});
		//新增后
		//self::event('after_insert', function ($_Data) {});
		//更新前
		//self::event('before_update', function($_Data) {});
		//更新后
		//self::event('after_update', function($_Data) {});
		//删除前
		//self::event('before_delete', function ($_Data) {});
		//删除后
		self::event('after_delete', function ($_Data) {
			model('app\admin\logic\Module')->_ResetCache();
		});
	}
	//自动完成
	protected function setCreateTimeAttr()
    {
        return time();
    }
	//自动完成
	protected function setUpdateTimeAttr()
    {
        return time();
    }
	//修改器
	//获取器
    public function getCreateTimeAttr($value,$data)
    {
		return date("Y-m-d H:i:s",$value);
    }
	public function getUpdateTimeAttr($value,$data)
    {
		return date("Y-m-d H:i:s",$value);
    }
}